package pannel.book;

import utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDao {
    private static final String TABLE_NAME = "book";

    // 新增图书
    public boolean insert(Book book) throws SQLException {
        String sql = "INSERT INTO " + TABLE_NAME +
                " (name, author, publisher, status, borrower_id, borrow_time, image_path) " +
                " VALUES (?, ?, ?, ?, ?, ?, ?)";
        int affected = (int) JDBCUtils.execute(sql,
                book.getName(),
                book.getAuthor(),
                book.getPublisher(),
                book.getStatus(),
                book.getBorrowerId(),
                book.getBorrowTime(),
                book.getImagePath()
        );
        return affected > 0;
    }

    // 更新图书信息
    public boolean updateById(Book book) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME +
                " SET name = ?, author = ?, publisher = ?, status = ?, " +
                " borrower_id = ?, borrow_time = ?, image_path = ? " +
                " WHERE id = ?";
        int affected = (int) JDBCUtils.execute(sql,
                book.getName(),
                book.getAuthor(),
                book.getPublisher(),
                book.getStatus(),
                book.getBorrowerId(),
                book.getBorrowTime(),
                book.getImagePath(),
                book.getId()
        );
        return affected > 0;
    }

    // 删除图书
    public boolean deleteById(Integer id) throws SQLException {
        String sql = "DELETE FROM " + TABLE_NAME + " WHERE id = ?";
        int affected = (int) JDBCUtils.execute(sql, id);
        return affected > 0;
    }

    // 分页模糊查询
    public List<Book> pageQuery(String name, Integer pageNum, Integer pageSize) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE name LIKE ? LIMIT ?, ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql,
                "%" + (name != null ? name : "") + "%",
                (pageNum - 1) * pageSize,
                pageSize
        );

        List<Book> books = new ArrayList<>();
        while (rs.next()) {
            books.add(mapResultSetToBook(rs));
        }
        return books;
    }

    // 获取总记录数
    public int getTotalCount(String name) throws SQLException {
        String sql = "SELECT COUNT(*) as total FROM " + TABLE_NAME + " WHERE name LIKE ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql,
                "%" + (name != null ? name : "") + "%"
        );
        return rs.next() ? rs.getInt("total") : 0;
    }

    // 借书
    public boolean borrowBook(Integer bookId, Integer borrowerId) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME +
                " SET status = ?, borrower_id = ?, borrow_time = ? " +
                " WHERE id = ? AND status = ?";
        int affected = (int) JDBCUtils.execute(sql,
                Book.STATUS_BORROWED,
                borrowerId,
                new java.util.Date(),
                bookId,
                Book.STATUS_AVAILABLE
        );
        return affected > 0;
    }

    // 还书
    public boolean returnBook(Integer bookId) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME +
                " SET status = ?, borrower_id = NULL, borrow_time = NULL " +
                " WHERE id = ? AND status = ?";
        int affected = (int) JDBCUtils.execute(sql,
                Book.STATUS_AVAILABLE,
                bookId,
                Book.STATUS_BORROWED
        );
        return affected > 0;
    }
    /**
     * 查询用户当前借阅的图书
     * @param borrowerId 借阅人ID
     * @return 该用户当前借阅的图书列表
     * @throws SQLException SQL异常
     */
    public List<Book> queryUserBorrowBooks(Integer borrowerId) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME +
                " WHERE borrower_id = ? AND status = ? " +
                " ORDER BY borrow_time DESC";

        ResultSet rs = (ResultSet) JDBCUtils.execute(sql,
                borrowerId,
                Book.STATUS_BORROWED  // 1-借出状态
        );

        List<Book> books = new ArrayList<>();
        while (rs.next()) {
            books.add(mapResultSetToBook(rs));
        }
        return books;
    }
    // ResultSet 映射到 Book 对象
    private Book mapResultSetToBook(ResultSet rs) throws SQLException {
        return Book.builder()
                .id(rs.getInt("id"))
                .name(rs.getString("name"))
                .author(rs.getString("author"))
                .publisher(rs.getString("publisher"))
                .status(rs.getInt("status"))
                .borrowerId(rs.getInt("borrower_id"))
                .borrowTime(rs.getTimestamp("borrow_time"))
                .imagePath(rs.getString("image_path"))
                .build();
    }
}